<template>
  <div class="upload-box">
    <div class="invoice-img-box">
      <div
        v-if="!invoiceUrl"
        class="invoice-upload-box"
        v-loading="upLoadLoading">
        <el-upload
          action="string"
          :disabled="disabled"
          :show-file-list="false"
          :accept="imageLimit"
          :http-request="toRequest"
          fit="scale-down"
        >
          <div class="upload-box">
            <div class="upload">
              <el-image
                style="width: 20px; height: 20px;"
                :src="uploadImg"/>
              <p>上传附件</p>
            </div>
            <p class="upload-tips">支持JPEG、PNG、PDF文件,不超过20MB</p>
          </div>
        </el-upload>
        <div class="m-upload">
          <auto-upload
            action="fileUpload"
            :disabled="disabled"
            :m-props="{urlObj:qrcodeImg,urlStr:'url'}"
          />
        </div>
      </div>
      <div
        v-else
        style="padding-top:16px; padding-left:8px;">
        <div
          ref="viewer"
          v-if="!isPdf"
          v-viewer>
          <el-image
            style="width: 266px; height: 189px;"
            :src="invoiceUrl"
            fit="cover"/>
        </div>
        <div
          ref="viewer"
          v-else
          @click="toPreview">
          <el-image
            style="width: 266px; height: 189px;"
            :src="pdfImg"
            fit="cover"/>
        </div>
        <div
          class="verification-info-box"
          @click="goBack(verificationState)"
          v-if="verificationState !== 4">
          <el-image
            v-if="tipsObj.tipsUrl"
            style="width: 24px; height: 24px;"
            :src="tipsObj.tipsUrl"
          />
          <p>{{ tipsObj.tipsInfo }}</p>
        </div>
        <!-- 验证通过显示的内容 -->
        <div
          class="verification-success-box"
          v-if="verificationState === 4">
          <!-- <el-tag type="success" class="tag">验真通过</el-tag> -->
          <div class="look-tips">
            <el-tag
              type="success"
              class="tag">验真通过</el-tag>
            <div @click="toPreview">
              <p>
                <el-image
                  style="width: 24px; height: 24px;"
                  :src="enlargeImg"/>
              </p>
              <p>点击放大查看</p>
            </div>
          </div>
          <div class="btn-box">
            <div @click="toPreview">
              <p class="p-border-right">
                <el-image
                  style="width: 16px; height: 16px;"
                  :src="previewImg"/>
              </p>
              <p>预览</p>
            </div>
            <div @click="toDownload">
              <p class="p-border-right">
                <el-image
                  style="width: 16px; height: 16px;"
                  :src="downloadImg"/>
              </p>
              <p>下载</p>
            </div>
            <div @click="toPrinting">
              <p>
                <el-image
                  style="width: 16px; height: 16px;"
                  :src="printingImg"/>
              </p>
              <p>打印</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import ElEditable from '@components/el-editable'
import AutoUpload from '@components/auto-upload'
import { previewUrl, previewUrlInfo } from '@const/common'
import { fileUpload } from '@const/api.js'
import { urlDownload } from '@const/utils.js'
import { formatDate } from '@const/filter.js'
import { _print } from '@const/print.js'
export default {
  components: { ElEditable, AutoUpload },
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    fileUpload: {
      type: String,
      default: fileUpload
    }, // 发票验证状态（1查验中，2通过，3失败，4完成）
    verificationState: {
      type: Number,
      default: 4
    },
    invoiceUrl: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      upLoadLoading: false,
      imageLimit: '.jpeg, .jpg, .png, .pdf',
      typeList: ['png', 'jpeg', 'jpg', 'PNG', 'JPEG', 'JPG', 'PDF', 'pdf'],
      errorTips: require('@assets/icon/beforeSettle/error.png'),
      successTips: require('@assets/icon/beforeSettle/success.png'),
      downloadImg: require('@assets/icon/beforeSettle/download.png'),
      previewImg: require('@assets/icon/beforeSettle/preview.png'),
      printingImg: require('@assets/icon/beforeSettle/printing.png'),
      uploadImg: require('@assets/icon/beforeSettle/upload.png'),
      enlargeImg: require('@assets/icon/beforeSettle/enlarge.png'),
      pdfImg: require('@assets/img/pdf.png'),
      qrcodeImg: {
        url: ''
      }
    }
  },
  watch: {
    'qrcodeImg.url' (val) {
      if (!val) return
      // 校验图片格式
      let type = val.substring(val.lastIndexOf('.') + 1)
      let isImage = this.typeList.includes(type)
      if (!isImage) {
        this.$message.error('上传文件只能是PNG、JPEG格式!')
        return false
      }

      this.$emit('returnUrl', val)
      this.qrcodeImg.url = ''
    }
  },
  computed: {
    tipsObj () {
      let obj = {}
      if (this.verificationState === 1) {
        obj = {
          tipsUrl: '',
          tipsInfo: '查验中...'
        }
      } else if (this.verificationState === 2) {
        obj = {
          tipsUrl: this.successTips,
          tipsInfo: '验真通过！'
        }
      } else if (this.verificationState === 3) {
        obj = {
          tipsUrl: this.errorTips,
          tipsInfo: '验真失败'
        }
      }
      return obj
    },
    isPdf () {
      return /\.pdf$/.test(this.invoiceUrl)
    }
  },
  methods: {
    goBack (val) {
      if (val === 3) {
        this.$emit('returnUrl', '')
      }
    },
    /**
     * 预览
     * 图片预览和pdf预览方式不同
     */
    toPreview () {
      // this.$refs.viewer.click()
      if (this.isPdf) {
        return void this.$pdfViewer({
          url: this.invoiceUrl,
          title: '预览'
        })
      }
      this.$refs.viewer.querySelector('img') && this.$refs.viewer.querySelector('img').click()
    },
    // 下载
    toDownload () {
      // 可惜了名字改不了
      const time = formatDate(new Date(), 'YYYYMMDDHH:mm:ss')
      urlDownload(this.invoiceUrl, `发票${time}`)
    },
    /**
     * 打印
     * 图片打印和pdf打印方式不同
     */
    toPrinting () {
      if (this.isPdf) {
        // 这里采用公共pdf预览的打印功能
        return void this.$pdfViewer({
          url: this.invoiceUrl,
          title: '打印',
          isPrint: true
        })
        // return void _print(`
        //   <div style="width:100%; height: 10000px;">
        //     <iframe width="1000px" height="100%" src="${previewUrlInfo}${this.invoiceUrl}"></iframe>
        //   </div>
        // `)
      }
      // 图片打印
      const png = new Image()
      png.src = this.invoiceUrl
      document.body.appendChild(png)
      png.onload = () => {
        let { width, height } = png
        let directionLevel = width > height
        _print(`<div style="width:100%;height:100%;display: flex;justify-content: center;align-items: center;">
          <img style=${directionLevel ? `-ms-transform:rotate(90deg);-moz-transform:rotate(90deg);-webkit-transform:rotate(90deg);-o-transform:rotate(90deg);` : ''}
            src=${this.invoiceUrl} width=${directionLevel ? '120%' : '70%'}/>
          </div>`)
        png.remove()
      }
    },
    toRequest (data) {
      // 图片拦截
      let FileType = data.file.name.split('.')

      const isImage = this.typeList.includes(FileType[1])
      if (!isImage) {
        this.$message.error('上传文件只能是PNG、JPEG格式!')
        return false
      }
      const isNumM = data.file.size / 1024 / 1024 < 20
      if (!isNumM) {
        this.$message.error('上传文件大小不能超过 20MB!')
        return false
      }
      this.upLoadLoading = true
      // 发起请求
      let fd = new FormData()
      fd.append('file', data.file)
      this.$axios({
        method: 'post',
        url: this.fileUpload,
        headers: { 'Content-Type': 'multipart/form-data' },
        data: fd
      }).then(res => {
        // this.$message({ type: 'success', message: '上传成功' })
        // 赋值上传后的地址给文档
        let invoiceUrl = res.data.payload
        if (invoiceUrl) {
          this.$emit('returnUrl', invoiceUrl)
        }
        this.upLoadLoading = false
      })
    }
  }
}
</script>
<style lang="less" scoped>
.upload-box {
  background: #fff;
  .invoice-img-box {
    padding: 0 0 16px 0;
    // padding-bottom: 16px;
    // border: 1px solid red;
    position: relative;
    .invoice-upload-box {
      // border: 1px solid red;
      padding-top: 16px;
      padding-left: 8px;
      display: flex;
      .upload-box {
        .upload {
          width: 158px;
          height: 53px;
          border: 1px solid #e8e8e8;
          display: flex;
          justify-content: center;
          align-items: center;
          font-size: 14px;
          color: #9ca6c7;
          p {
            margin-left: 10px;
          }
        }
        .upload-tips {
          font-size: 14px;
          color: #9ca6c7;
          margin-top: 20px;
          text-align: left;
        }
      }
      /deep/.m-upload {
        position: absolute;
        top: 6px;
        left: 220px;
        .el-button--primary {
          color: #2371c5;
          background: #fff;
          border-radius: 0;
          border: 1px solid #2371c5;
          font-size: 20px;
          padding: 0;
        }
        .qrcode_upload_box .icon-qrcode {
          font-size: 50px;
        }
      }
    }
  }
  .verification-info-box {
    width: 266px;
    height: 189px;
    background: rgba(0, 0, 0, 0.6);
    position: absolute;
    left: 8px;
    top: 16px;
    color: #fff;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    p {
      margin: 5px 0;
    }
  }
  .verification-success-box {
    width: 266px;
    height: 189px;
    position: absolute;
    left: 8px;
    top: 16px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: flex-end;
    .look-tips {
      width: 266px;
      height: 132px;
      color: #fff;
      display: flex;
      justify-content: center;
      align-items: center;
      div {
        display: none;
        width: 266px;
        text-align: center;
        margin: 0 auto;
        p {
          margin-top: 10px;
        }
      }
      .tag {
        position: absolute;
        right: 1px;
        top: 1px;
      }
    }
    .look-tips:hover {
      div {
        display: block;
        cursor: pointer;
      }

      background: rgba(0, 0, 0, 0.6);
    }
    .btn-box {
      width: 266px;
      height: 57px;
      background: #f7f9fa;
      display: flex;
      align-items: center;
      div {
        width: 33.33%;
        cursor: pointer;
        .p-border-right {
          border-right: 1px solid #e8e8e8;
        }
        p {
          text-align: center;
          font-size: 12px;
        }
      }
    }
  }
}
</style>
